local modname = minetest.get_current_modname()
local S = minetest.get_translator(modname)

if not throwables then return end

-- Add a throwable fireball
local fireball = throwables:new(modname .. ":fireball", {
    description = S("Fireball").."\n"..
        S("Left click to throw it@nIt will explode on impact causing damage and fire"),
    inventory_image = "fireball.png",
    stack_max = 16,
    initial_properties = {
        hp_max = 1,
        physical = true,
        collide_with_objects = true,
        collisionbox = {-0.2, -0.2, -0.2, 0.2, 0.2, 0.2},
        visual = "wielditem",
        visual_size = {x = 0.4, y = 0.4},
        textures = {modname .. ":fireball"},
        spritediv = {x = 1, y = 1},
        initial_sprite_basepos = {x = 0, y = 0},
        pointable = false,
        speed = 40,
        gravity = 9.81,
        damage = 4,
        lifetime = 8
    },
})

-- Explode function for callbacks
local function explode(self)
    local pos = self.object:get_pos()

    minetest.sound_play("fireball_explode", {max_hear_distance = 10, pos = pos})
    minetest.add_particlespawner({
        amount = 50,
        time = 1,
        minpos = pos,
        maxpos = pos,
        minvel = {x = -2, y = -2, z = -2},
        maxvel = {x = 2, y = 2, z = 2},
        minacc = {x = 0, y = -10, z = 0},
        maxacc = {x = 0, y = -10, z = 0},
        minexptime = 1,
        maxexptime = 2,
        minsize = 1,
        maxsize = 3,
        collisiondetection = true,
        collision_removal = true,
        object_collision = true,
        vertical = false,
        texture = "fireball_smoke.png",
    })

    local objects = minetest.get_objects_inside_radius(pos, 3)
    for _, obj in ipairs(objects) do
        if obj:is_player() then
            obj:set_hp(obj:get_hp() - self.initial_properties.damage)
            obj:set_pos(vector.add(obj:get_pos(), {x = 0, y = 1, z = 0}))
            obj:add_player_velocity({x = 0, y = 5, z = 0})
        end
    end

    minetest.set_node(pos, {name = "fire:basic_flame"})
    self.object:remove()
end


-- Callbacks functions
local function on_hit_node(self, node)
    explode(self)
end

local function on_hit_entity(self, entity)
    explode(self)
end

-- Register callbacks
fireball:on_hit_node(on_hit_node)
fireball:on_hit_entity(on_hit_entity)
